let App = getApp();
let time = require('../../utils/util.js');
var dateTimePicker = require('../../utils/dateTimePicker.js');
//截取最后一个后面的字符
function substringLast(str) {
  str = str.substring(0,str.length-1);
  return str
}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    school:["宝山校区","浦东校区","嘉定校区"],
    orderType:['待处理','待回访','待支付','已完成','已取消','待结算','已结算'],
    intention:['好','中','差'],
    classLevel: [],
    order:"",
    date:"",
    orderId:0,
    timeArray: null,
    visitTime: null,
    visitTimeIndex: [],
    freeTime: null,
    freeTimeIndex: [],
    isReturn:true,
    isShow:false,
    multiIndex: [0, 0],
    phone:'',
    isDis:true,
    hiddenmodalput:true,
    multiArray: [],
    typeIndex:1,
    reason:"",
    intentionIndex: 1, // 意向下拉默认索引
    classLevelIndex: 0, // 学车课程默认下拉索引
    params: {
      schoolid: '', // 学校id 下拉列表
      classid: '', // 班级 下拉列表
      class_level: '', // 学车课程，下拉列表
      address: '', // 地址 字符串
      free_time: '请选择试学时间', // 试学时间 datetime格式，就是2020-01-22 10:00:00这种
      remark: '', // 备注
      pay_method: 3, // 支付方式 1=支付宝；2=微信；3=门店支付
      intention: 2, // 意向 1好 2中 3差
      order_status: '', // 订单状态 1=未处理；2=待回访；3=待支付；4=已完成；5=已取消；6=待结算；7=已结算
      order_id: '', // 需要修改的订单id
      return_visit_time: '请选择回访时间', // 回访时间 datetime格式
    },
    paramsError: {
      schoolid: '请选择学区', // 学校id 下拉列表
      classid: '请选择班级', // 班级 下拉列表
      class_level: '请选择学车课程', // 学车课程，下拉列表
      address: '请填写接送地址', // 地址 字符串
      free_time: '请选择预约试学时间', // 试学时间 datetime格式，就是2020-01-22 10:00:00这种
      remark: '请填写备注', // 备注
      pay_method: '', // 支付方式 1=支付宝；2=微信；3=门店支付
      intention: '请选择意向', // 意向 1好 2中 3差
      order_status: '', // 订单状态 1=未处理；2=待回访；3=待支付；4=已完成；5=已取消；6=待结算；7=已结算
      order_id: '', // 需要修改的订单id
      return_visit_time: '请选择回访时间', // 回访时间 datetime格式
    }
  },
  getRemark(){
    if(this.data.isShow == false ){
      this.setData({
        isShow:true
      })
    }else{
      this.setData({
        isShow:false
      })
    }
   
  },
  //选择订单状态e
  bindTypeChange:function(e){
    this.setData({
      typeIndex: e.detail.value
    })
  },
  //选择校区
  bindMultiPickerChange: function (e) {
    const {multiArray} = this.data
    const value = e.detail.value
    this._getClassLevelBySchoolId(multiArray[1][value[1]].id)
    this.setData({
      multiIndex: e.detail.value
    })
  },
  bindMultiPickerColumnChange: function (e) {
    const {multiArray, multiIndex} = this.data
    multiIndex[e.detail.column] = e.detail.value;
    if(e.detail.column === 0) {
      let id = multiArray[0][e.detail.value].id
      this.schoo(id)
    }
  },
  //拨打电话
  callPhone(){
    wx.makePhoneCall({
      phoneNumber: this.data.phone //仅为示例，并非真实的电话号码
    })
  },
  formSubmit(e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
  },
  //获取校区
  schoolList(){
    let that = this
    App._get(App.Domain+'Handler/Applet/getAllAreas', {}, function (result) {
        if(result.code == 1){
          let multiArray = that.data.multiArray
          multiArray.push(result.data)
          that.setData({
            multiArray
          })
          that.schoo(result.data[0].id)
        }
    })
  },
  //根据校区获取学校
  schoo(id){
    let that = this
    App._get(App.Domain+'Handler/Applet/getSchoolsByAreaId', {areaid:id}, (result) =>{
        if(result.code == 1){
          let multiArray = that.data.multiArray
          if(multiArray.length>1){
            multiArray.splice(1,1)
          }
          multiArray.push(result.data)
          let multiIndex = this.data.multiIndex
          multiIndex[1] = 0 // 将第二列索引设置成第一个数据
          that.setData({
            multiArray,
            multiIndex,
          })
          console.log(that.data.multiArray)
          this._getClassLevelBySchoolId(result.data[0].id)
        }
    })
  },
  // 根据学校获取课程
  _getClassLevelBySchoolId(id){
    App._get(App.Domain+'Handler/Applet/getClassLevelBySchoolId', {schoolid: id}, (result) =>{
        if(result.code == 1){
          this.setData({
            classLevel: result.data
          })
        }
    })
  },
  formReset(e) {
    console.log('form发生了reset事件，携带数据为：', e.detail.value)
    this.setData({
      chosen: ''
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  //日期选择
  bindDateChange: function(e) {
    const value = e.detail.value
    const { paramkey } = e.currentTarget.dataset
    const timeArray = this.data.timeArray
    const dateStr = `${substringLast(timeArray[0][value[0]])}-${substringLast(timeArray[1][value[1]])}-${substringLast(timeArray[2][value[2]])} ${substringLast(timeArray[3][value[3]])}:${substringLast(timeArray[4][value[4]])}`
    if(paramkey=='return_visit_time') {
      this.setData({
        visitTimeIndex: value,
      });
    }
    else {
      this.setData({
        freeTimeIndex: value
      });
    }
    const params = this.data.params
    params[paramkey] = dateStr
    this.setData({
      params
    })
  },
  changeDateTimeColumn(e) {
    const { paramkey } = e.currentTarget.dataset
    const dateArr = this.data.timeArray;
    if(paramkey=='return_visit_time') {
      let arr = this.data.visitTime
      arr[e.detail.column] = e.detail.value;
      dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]].replace("月", ''), '日');
      this.setData({
        visitTime: arr
      });
    }
    else {
      let arr = this.data.freeTime
      arr[e.detail.column] = e.detail.value;
      dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]].replace("月", ''), '日');
      this.setData({
        freeTime: arr
      });
    }
  },
  // 意向选择
  bindIntentionChange(e) {
    this.setData({
      intentionIndex: e.detail.value
    })
  },
  // 课程选择
  bindclassLevelChange(e) {
    this.setData({
      classLevelIndex: e.detail.value
    })
  },
  // 文本框input事件
  onBindInput:function(e){
    const params = this.data.params
    const { paramkey } = e.currentTarget.dataset
    params[paramkey] = e.detail.value
    this.setData({
      params: params
    })
  },
  // 提交订单回访
  submitConfirm() {
    const {multiArray, multiIndex, params, paramsError, order, intention, intentionIndex, classLevel, classLevelIndex} = this.data
    params.schoolid = multiArray[0][multiIndex[0]].id
    params.classid = multiArray[1][multiIndex[1]].id
    params.intention = intention[intentionIndex]
    params.class_level = classLevel[classLevelIndex].id
    params.order_id = order.id
    params.order_status = parseInt(this.data.typeIndex)+1
    if(params.intention == '好'){
      params.intention = 1
    }else if(params.intention == '中'){
      params.intention = 2
    }else{
      params.intention = 3
    }
    for (const key in params) {
      if(key=='address') {
        continue
      }
      if(key=='free_time') {
        continue
      }
      if(typeof(params[key]) == 'string') params[key] = params[key].trim()
      if (!params[key]) {
        wx.showToast({
          icon:'none',
          title: paramsError[key]
        });
        return false;
      }
    }
    App._post(App.Domain+'Handler/Applet/updateNotDeal', params, function (result) {
      if(result.code == 1){
        wx.navigateBack({
          delta: 1
        })
      }
    })
  },
  setDate() {
    // 获取完整的年月日 时分秒，以及默认显示的数组
    // const {startYear, endYear} = this.data
    let dateNow = new Date();
    let year = dateNow.getFullYear();
    let month = dateNow.getMonth() + 1;
    month = month < 10 ? ('0'+month) : month
    let day = dateNow.getDate()
    day = day < 10 ? ('0'+day) : day
    let hour = dateNow.getHours()
    hour = hour < 10 ? ('0'+hour) : hour
    let minutes = dateNow.getMinutes();
    minutes = minutes < 10 ? ('0'+minutes) : minutes
    let startYear = year - 20
    let endYear = year + 20
    let defaultDate = `${year}年-${month}月-${day}日 ${hour}时:${minutes}分`
    var obj = dateTimePicker.dateTimePicker(startYear, endYear, defaultDate);
    this.setData({
      timeArray: obj.dateTimeArray,
      visitTimeIndex: obj.dateTime,
      freeTimeIndex: obj.dateTime,
    });
  },
  // 处理详情返回的时间参数，将其换算成正确的格式
  handleDateParmas(date, type) {
    if(type == 1) {
      date = new Date(parseInt(date))
    }
    else {
      date = new Date(date)
    }
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    month = month < 10 ? ('0'+month) : month
    let day = date.getDate()
    day = day < 10 ? ('0'+day) : day
    let hour = date.getHours()
    hour = hour < 10 ? ('0'+hour) : hour
    let minutes = date.getMinutes();
    minutes = minutes < 10 ? ('0'+minutes) : minutes
    return `${year}-${month}-${day} ${hour}:${minutes}`
  },
  onLoad: function (options) {
    let id = options.id
    let that = this
    that.setData({
      orderId:id
    })
    App._get(App.Domain+'Handler/Applet/getOrderDetail', {order_id:id}, function (result) {
        if(result.code == 1){
          const order = result.data.order
          if(order.remark){
            that.setData({
              isDis:false
            })
          }
          const remark = ''
          let isReturn = true
          if(Array.isArray(remark) && remark.length>0){
            isReturn = false
          }
          const params = that.data.params
          order.free_time = that.handleDateParmas(order.free_time)
          // order.return_visit_time = that.handleDateParmas(order.return_visit_time, 1)
          order.return_visit_time = time.formatTime(new Date())
          // params.address = address
          for (const key in params) {
            if(key=='remark' || key == 'address' || key == "free_time") {
              continue
            }
            params[key] = order[key]
          }
          that.setData({
            params,
            isReturn,
            phone:order.mobile,
            order,
            date:time.formatTime(parseInt(result.data.order.return_visit_time)*1000,'Y/M/D h:m:s')
          })
          that.setDate()
        }
    })
  },
  cancelOrder(){
    this.setData({
      hiddenmodalput:false
    })
  },
  confirmM(){
  if(this.data.reason == ''){
    wx.showToast({
      title: '请填写取消原因',
      icon: 'none',
      duration: 2000
    })
  }else{
    let data = {
      order_id:this.data.orderId,
      cancel_reason:this.data.reason
    }
    App._post(App.Domain+'Handler/Applet/channelOrder', data, function (result) {
      if(result.code == 1){
        wx.navigateBack({
          delta: 1
        })
      }
    })
  }
},
cancelM(){
  this.setData({
    hiddenmodalput:true
  })
},
bindTextAreaBlur(e){
  this.setData({
    reason:e.detail.value
  })
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.schoolList()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})